package de.baumann.browser.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

import de.baumann.browser.OdinGlideModule;
import de.baumann.browser.R;

public class ImageListAdapter extends RecyclerView.Adapter {

    private Context mContext;
    private List<String> data = new ArrayList<>();
    private OnClickAddImageListener addImageListener;

    public ImageListAdapter(Context mContext, OnClickAddImageListener addImageListener) {
        this.mContext = mContext;
        this.addImageListener = addImageListener;
    }

    public void addData(String path) {
        this.data.add(path);
        notifyDataSetChanged();
    }

    public List<String> getDatas(){
        return data;
    }



    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View rootView = LayoutInflater.from(mContext).inflate(R.layout.recycler_item_image, parent, false);
        return new ViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ViewHolder viewHolder = (ViewHolder) holder;
        if (data == null || data.size() <= 0 || position == data.size()) {
            viewHolder.ivThumbnail.setImageResource(R.drawable.ic_camera);
            viewHolder.ivDel.setVisibility(View.GONE);
            viewHolder.ivThumbnail.setOnClickListener(view -> {
                if (addImageListener != null) {
                    addImageListener.clickAddImage();
                }
            });
            return;
        }

        OdinGlideModule.loadWithCrop(mContext, data.get(position), viewHolder.ivThumbnail, R.drawable.shape_default_cover);
        viewHolder.ivDel.setVisibility(View.VISIBLE);
        viewHolder.ivDel.setOnClickListener(view -> {
            data.remove(position);
            notifyDataSetChanged();
        });
    }

    @Override
    public int getItemCount() {
        return data == null || data.size() == 0 ? 1 : data.size() + 1;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivThumbnail;
        ImageView ivDel;

        ViewHolder(View itemView) {
            super(itemView);
            ivThumbnail = itemView.findViewById(R.id.ivThumbnail);
            ivDel = itemView.findViewById(R.id.ivDel);
        }
    }

    public interface OnClickAddImageListener {
        void clickAddImage();
    }

}
